package com.examples.gateway.helper.entity;

import com.examples.gateway.common.CheckState;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Getter
public class ResponseContext {

    private HttpStatus httpStatus;

    private CheckState checkState;

    private static final Set<CheckState> UNAUTHORIZED = new HashSet<>(Arrays.asList(
            CheckState.PERMISSION_ACCESS_TOKEN_NULL,
            CheckState.PERMISSION_ACCESS_TOKEN_INVALID,
            CheckState.PERMISSION_ACCESS_TOKEN_EXPIRED,
            CheckState.PERMISSION_GET_USE_DETAIL_FAILED
    ));

    public void setHttpStatus(HttpStatus httpStatus) {
        this.httpStatus = httpStatus;
    }

    public void setCheckState(CheckState state) {
        this.checkState = state;
        if (null != state ) {
            if (state.value() < HttpStatus.MULTIPLE_CHOICES.value()) {
                // 成功
                setHttpStatus(HttpStatus.OK);
            } else if (UNAUTHORIZED.contains(state)) {
                // 未授权
                setHttpStatus(HttpStatus.UNAUTHORIZED);
            }else if (HttpStatus.NOT_FOUND.value() == state.value()) {
                // 文件未找到
                setHttpStatus(HttpStatus.NOT_FOUND);
            } else if (state.value() < HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                // 拒绝访问
                setHttpStatus(HttpStatus.FORBIDDEN);
            } else if (state == CheckState.PERMISSION_SERVICE_ROUTE || state == CheckState.PERMISSION_SERVICE_INSTANCE) {
                setHttpStatus(HttpStatus.SERVICE_UNAVAILABLE);
            } else {
                // 服务异常
                setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
    }

}
